//
//  XiaoximenSelectPersonViewController.m
//  Xiaoximen_iOS
//
//  Created by Wang Zhongyu on 12-7-19.
//  Copyright (c) 2012年 Peking University. All rights reserved.
//

#import "XiaoximenSelectPersonViewController.h"
#import "XiaoximenPostViewController.h"
#import "XiaoximenAppDelegate.h"
#import "ASIHTTPRequest.h"

@interface XiaoximenSelectPersonViewController () {
	BOOL bRequest;
	ASIHTTPRequest *requestParty;
	ASIHTTPRequest *requestPlaces;
	ASIHTTPRequest *requestTimes;
	int invitation_id;
	NSString *shortURL;
	
	int place_index;
	int time_index;
}

@end

@implementation XiaoximenSelectPersonViewController
@synthesize persons;
@synthesize images;
@synthesize yess;
@synthesize parentDataSource;
@synthesize delegate;
@synthesize progressHub;

- (NSObject<PABezelHUDDelegate> *)delegate {
    if (delegate == nil) {
        delegate = (NSObject<PABezelHUDDelegate> *)[UIApplication sharedApplication].delegate;
    }
    return delegate;
}
- (MBProgressHUD *)progressHub{
    if (progressHub == nil) {
        progressHub = self.delegate.progressHub;
    }
    return progressHub;
}
- (void)showProgressHubWithTitle:(NSString *)title{
    self.progressHub.mode = MBProgressHUDModeIndeterminate;
	self.progressHub.delegate = nil;
    self.progressHub.labelText = title;
    [self.progressHub show:YES];
}
- (void)changeProgressHub:(NSString *)title
{
	progressHub.animationType = MBProgressHUDAnimationZoom;
    self.progressHub.labelText = title;
    self.progressHub.mode = MBProgressHUDModeCustomView;
    [self.progressHub hide:YES afterDelay:1];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	
	UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] init];
	barButtonItem.title = @"添加人物";
	self.navigationItem.backBarButtonItem = barButtonItem;
	
	persons = [[NSMutableArray alloc] initWithObjects:@" 狼风师兄", @" 小冋前辈", @" 小芳助教", @" 张塔", @" 王仲禹", @" 谢家晔", @" 曹衫", nil];
	
	images = [[NSMutableArray alloc] init];
	for (int i = 0; i < persons.count; i++) {
		UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 43)];
		imageView.image = [UIImage imageNamed:@"text"];
		[images addObject:imageView];
	}
	
	yess = [[NSMutableArray alloc] init];
	for (int i = 0; i < persons.count; i++) {
		UIImageView *yes = [[UIImageView alloc] initWithFrame:CGRectMake(200, 12, 20, 20)];
		yes.image = [UIImage imageNamed:@"y"];
		[yess addObject:yes];
	}
	
	bRequest = NO;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return persons.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"personIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
	[cell addSubview:[images objectAtIndex:indexPath.row]];
	UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 11, 180, 21)];
	label.text = [persons objectAtIndex:indexPath.row];
	label.font = [UIFont boldSystemFontOfSize:17];
	label.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.0];
	[cell addSubview:label];
	
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
	if ([segue.identifier isEqualToString:@"PostSegue"]) {
		[segue.destinationViewController setMessage:[NSString stringWithFormat:@"%@邀请您参加“%@”活动，请投票选择地点时间。请戳链接%@", [[NSUserDefaults standardUserDefaults] objectForKey:kNAME], parentDataSource.partyTitle, shortURL]];
	}
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	if ([[[yess objectAtIndex:indexPath.row] superview] isEqual:cell]) {
		[[yess objectAtIndex:indexPath.row] removeFromSuperview];
		UIImageView *image = [images objectAtIndex:indexPath.row];
		image.image = [UIImage imageNamed:@"text"];
	} else {
		[cell addSubview:[yess objectAtIndex:indexPath.row]];
		UIImageView *image = [images objectAtIndex:indexPath.row];
		image.image = [UIImage imageNamed:@"textfield"];
	}
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (IBAction)onNext:(id)sender {
	if (bRequest) return ;
	bRequest = YES;
	[self showProgressHubWithTitle:@"提交中...先别点哦^_^"];
	
	int user_id = [[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"] intValue];
	
	NSString *urlString = [NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/add?user_id=%d&title=%@", user_id, parentDataSource.partyTitle];
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSLog(@"%@", urlString);
	NSURL *urlParty = [NSURL URLWithString:urlString];
	requestParty = [ASIHTTPRequest requestWithURL:urlParty];
	[requestParty setDelegate:self];
	[requestParty setTimeOutSeconds:20];
	[requestParty startAsynchronous];
}

- (NSDate *)startDateFromTimeInterval:(NSString *)timeInterval
{
	NSString *startTime = [[timeInterval substringToIndex:17] stringByAppendingString:@":00"];
	startTime = [startTime stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
	startTime = [startTime stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
	startTime = [startTime stringByReplacingOccurrencesOfString:@"日" withString:@""];
	
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
	NSDate *startDate = [[NSDate alloc] init];
	startDate = [formatter dateFromString:startTime];
	return startDate;
}

- (NSDate *)endDateFromTimeInterval:(NSString *)timeInterval
{
	NSString *endTime = [[NSString stringWithFormat:@"%@%@", [timeInterval substringToIndex:12], [timeInterval substringFromIndex:18]] stringByAppendingString:@":00"];
	endTime = [endTime stringByReplacingOccurrencesOfString:@"年" withString:@"-"];
	endTime = [endTime stringByReplacingOccurrencesOfString:@"月" withString:@"-"];
	endTime = [endTime stringByReplacingOccurrencesOfString:@"日" withString:@""];
	
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
	NSDate *endDate = [formatter dateFromString:endTime];
	NSLog(@"%@", endTime);
	NSLog(@"%@", endDate);
	return endDate;
}


- (void)requestFinished:(ASIHTTPRequest *)request
{
	NSData *responseData = [request responseData];
	id res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONWritingPrettyPrinted error:nil];
	NSLog(@"%@", res);
	
	if ([request isEqual:requestParty]) {
		invitation_id = [[res objectForKey:kINVITATIONID] intValue];
		shortURL = [res objectForKey:kSHORTURL];
		place_index = 0;
		time_index = 0;
	}
	if (place_index < parentDataSource.selectedPlaces.count) {
		NSString *urlString = [NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/%d/option/place/add?place_name=%@", invitation_id, [parentDataSource.selectedPlaces objectAtIndex:place_index]];
		
		urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		NSLog(@"%@", urlString);
		NSURL *urlPlace = [NSURL URLWithString:urlString];
		requestPlaces = [ASIHTTPRequest requestWithURL:urlPlace];
		[requestPlaces setDelegate:self];
		[requestPlaces setTimeOutSeconds:20];
		[requestPlaces startAsynchronous];
		place_index ++;
	} else if (time_index < parentDataSource.selectedDates.count) {
		NSString *urlString = [NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/%d/option/time/add?time_start=%d&time_end=%d", invitation_id, (int)([[self startDateFromTimeInterval:[parentDataSource.selectedDates objectAtIndex:time_index]] timeIntervalSince1970]), (int)([[self endDateFromTimeInterval:[parentDataSource.selectedDates objectAtIndex:time_index]] timeIntervalSince1970])];
		
		urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		NSLog(@"%@", urlString);
		NSURL *urlTime = [NSURL URLWithString:urlString];
		requestTimes = [ASIHTTPRequest requestWithURL:urlTime];
		[requestTimes setDelegate:self];
		[requestTimes setTimeOutSeconds:20];
		[requestTimes startAsynchronous];
		time_index ++;
	} else {
		bRequest = NO;
		[self changeProgressHub:@"提交成功！"];
		
		NSMutableArray *invitationIDs = [[[NSUserDefaults standardUserDefaults] valueForKey:kINVITATIONIDS] mutableCopy];
		if (![invitationIDs containsObject:[NSString stringWithFormat:@"%d", invitation_id]]) [invitationIDs addObject:[NSString stringWithFormat:@"%d", invitation_id]];
		[[NSUserDefaults standardUserDefaults] setObject:invitationIDs forKey:kINVITATIONIDS];
		
		[self performSegueWithIdentifier:@"PostSegue" sender:self];
	}
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	NSError *error = [request error];
	NSLog(@"%@", error);
	bRequest = NO;
	[self changeProgressHub:@"提交失败><"];
	[self performSegueWithIdentifier:@"ErrorSegue" sender:self];
}

@end
